package com.sntk.registermanager.staff.infrastructure.dao;

import cn.hutool.core.util.RandomUtil;
import com.sntk.registermanager.common.exception.ObjectExistedException;
import com.sntk.registermanager.staff.domain.model.DoctorInfo;
import com.sntk.registermanager.staff.domain.repository.DoctorInfoRepository;
import com.sntk.registermanager.staff.infrastructure.convert.DoctorInfoConvert;
import com.sntk.registermanager.staff.infrastructure.db.entity.DoctorInfoEntity;
import com.sntk.registermanager.staff.infrastructure.db.repository.DoctorInfoDBRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName: DoctorInfoRepositoryImpl
 * @author: wgchao
 * @createTime: 2020/11/19 10:15 AM
 * @Description: TODO
 */
@Component
public class DoctorInfoRepositoryImpl implements DoctorInfoRepository {

    @Autowired
    private DoctorInfoDBRepository doctorInfoDBRepository;
    @Autowired
    private DoctorInfoConvert doctorInfoConvert;


    @Override
    public String generateDoctorCode() {
        String code = RandomUtil.randomNumbers(4);
        while (findByKey(code) != null) {
            code = RandomUtil.randomNumbers(4);
        }
        return code;
    }

    @Override
    public void add(DoctorInfo doctorInfo, String operator) {
        DoctorInfoEntity doctorInfoEntity = doctorInfoDBRepository.findFirstByDoctorCodeAndDelFalse(doctorInfo.getDoctorCode());
        if(doctorInfo.isAdd()){
            if(doctorInfoEntity != null){
                throw new ObjectExistedException("医生编号已被占用!");
            }

            doctorInfoEntity = doctorInfoConvert.convert(doctorInfo);
            doctorInfoEntity.setCreateTime(new Date())
            .setCreator(operator)
            .setDel(false);

            doctorInfoEntity = doctorInfoDBRepository.save(doctorInfoEntity);

        }else{

            if(doctorInfoEntity == null){
                throw new ObjectExistedException("医生编号已被占用!");
            }

            DoctorInfoEntity doctorInfoEntityNew = doctorInfoConvert.convert(doctorInfo);
            doctorInfoEntityNew.setCreator(doctorInfoEntity.getCreator())
            .setCreator(doctorInfoEntity.getCreator())
            .setLastUpdateTime(new Date())
            .setLastUpdator(operator)
            .setDel(doctorInfoEntity.getDel());

            doctorInfoEntityNew = doctorInfoDBRepository.save(doctorInfoEntityNew);
        }

    }

    @Override
    public DoctorInfo findByKey(String s) {
        DoctorInfoEntity doctorInfoEntity = doctorInfoDBRepository.findFirstByDoctorCodeAndDelFalse(s);
        return doctorInfoConvert.convert(doctorInfoEntity);
    }

    @Override
    public void delete(String s, String operator) {

    }
}
